<template>
  <div class="app-container">
    <el-card id="dlls_card" class="box-card" style="text-align: center;">
      <div style="width: 98%; margin: 0 auto">
        <div
          style="
          margin: 10px 0;
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 10px;
        "
        >
          <el-button
            type="primary"
            @click="handleShouQuan"
          >授权</el-button>
        </div>

        <div>
          <drag-head
            ref="dragHeadRef"
            :show-all-filter-condition="showAllFilterCondition"
            :store-names="storeName"
            :head-columns="tableHead"
            :data="backendUserList"
            :loading="loading"
            @handleSelectionChange="handleSelectionChange"
            @sort_change="sort_change"
            @openPddLinkDialog="openPddLinkDialog"
            @handleCommand="handleCommand"
            @openComment="openComment"
            @fresh="fresh"
          />
          <div class="" style="margin-top: 10px; float: right;margin-bottom: 10px;">
            <el-pagination
              :page-sizes="[10, 15, 20, 25, 50, 100, 200]"
              :current-page.sync="page"
              :page-size="page_size"
              layout="sizes, prev, pager, next, total"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-card>
    <el-dialog
      title="授权渠道"
      :visible.sync="shouquanPlatFormDialog.visible"
      class="updateDialog"
      width="1000px"
      append-to-body
    >
      <el-form
        ref="ruleForm"
        label-width="120px"
        style="display: flex"
        class="dialog-box-distinguish"
      >
        <el-form-item>
          <el-button
            type="danger"
            size="mini"
            @click="handleshouQuan(1)"
          >拼多多</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            size="mini"
            @click="handleshouQuan(2)"
          >小程序</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            size="mini"
            @click="handleshouQuan(3)"
          >淘宝</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="授权账户列表"
      :visible.sync="shouquanDetailDialog.visible"
      width="1000px"
      append-to-body
    >
      <div style="display: flex; margin-bottom: 10px">
        <el-input
          v-model="search"
          style="width: 200px; margin-right: 10px"
          placeholder="输入关键字搜索"
        />
        <el-button
          type="primary"
          size="mini"
          @click="checkShouQuanAccount"
        >勾选需要授权的帐号</el-button>
      </div>
      <div class="pddTable">
        <el-table
          v-loading="shouquanDetailDialog.loading"
          :data="
            shouquanDetailDialog.list.length > 0
              ? shouquanDetailDialog.list.filter(
                (data) =>
                  !search ||
                  data.name.toLowerCase().includes(search.toLowerCase())
              )
              : []
          "
          border
          style="width: 100%"
          @selection-change="handelShouquanListChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="status" label="绑定状态" />
          <el-table-column prop="bind_str" label="账户状态" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 户小时报表 hourPlanDialog.list-->
    <el-dialog
      title="户小时报表"
      :visible.sync="hourPlanDialog.visible"
      width="1000px"
      append-to-body
    >
      <div style="display: flex; margin-bottom: 10px">
        <span class="dataPicker">日期：</span>
        <el-date-picker
          v-model="hourPlanDialog.datetime"
          type="date"
          value-format="yyyy-MM-dd"
          @change="getHourList"
        />
      </div>
      <div class="pddTable">
        <el-table
          v-loading="hourPlanDialog.loading"
          :data="hourPlanDialog.list"
          max-height="600"
          border
          style="width: 100%; overflow: scroll; overflow-x: hidden"
        >
          <el-table-column prop="datetime" label="时间" width="150" />
          <!--          <el-table-column prop="cpa_bid" label="出价" width="100">-->
          <!--          </el-table-column>-->
          <el-table-column
            prop="cost"
            label="花费"
            width="100"
          />
          <el-table-column
            prop="effect_roi"
            label="有效roi"
            width="100"
          />
          <el-table-column
            prop="effect_sale"
            label="有效销售额"
            width="100"
          />
          <el-table-column
            prop="order_num"
            label="订单数"
            width="100"
          />
          <!--          <el-table-column-->
          <!--            prop="name"-->
          <!--            label="计划变动日志"-->
          <!--            width="200"-->
          <!--          ></el-table-column>-->
          <el-table-column prop="roi" label="roi" width="100" />
          <el-table-column
            prop="sale"
            label="销售额"
            width="100"
          />
          <!-- <el-table-column
            prop="budget"
            label="预算"
            width="100"
          ></el-table-column> -->
          <el-table-column
            prop="click"
            label="点击"
            width="100"
          />
          <el-table-column
            prop="show"
            label="展示"
            width="100"
          />
          <el-table-column
            prop="convert"
            label="转化"
            width="100"
          />
          <el-table-column
            prop="convert_cost"
            label="转化成本"
            width="100"
          />
        </el-table>
      </div>
    </el-dialog>

    <keep-alive>
      <router-view />
    </keep-alive>
  </div>
</template>

<script>
import {
  getBackendList,
  getLinearList,
  openRefund,
  getHourPlanList,
  openCommentControl,
  closeCommentControl,
  oauthUrl,
  getRecent,
  callBackDetail,
  callBackChoose
} from '../../api'
import DragHead from './dragHead.vue'
import NoticeBar from './noticeBar.vue'
import JsonExcel from 'vue-json-excel'
export default {
  components: { DragHead, DownloadExcel: JsonExcel, NoticeBar },
  data() {
    return {
      storeName: 'accountList',
      platForm: 1,
      pddLinkDialog: {
        // 多多直链弹窗
        visible: false,
        list: [],
        loading: false,
        currentAdvertiserId: undefined // 拼多多直链id
      },
      pickerOptions: {
        // 今天 昨天 最近三天 最近七天 本月 上个月
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick: (picker) => {
              const start = new Date()
              start.setTime(start.getTime() - 24 * 60 * 60 * 1000)
              start.setHours(0, 0, 0, 0)
              const end = new Date(start.getTime() + 24 * 60 * 60 * 1000 - 1)
              end.setHours(23, 59, 59, 999)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近七天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setDate(1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '上个月',
            onClick: (picker) => {
              const start = new Date()
              start.setMonth(start.getMonth() - 1, 1)
              start.setHours(0, 0, 0, 0)
              const end = new Date(
                start.getFullYear(),
                start.getMonth() + 1,
                0
              )
              end.setHours(23, 59, 59, 999)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      showAllFilterCondition: false,
      tableHead: [
        {
          label: '户ID',
          prop: 'advertiser_id',
          width: 90,
          sortable: false,
          show: true
        },
        {
          label: '户名',
          prop: 'name',
          width: 90,
          sortable: false,
          show: true
        },
        {
          label: '备注',
          prop: 'note',
          width: 90,
          sortable: false,
          show: true
        },
        {
          label: '自动回评',
          prop: 'comment_auto_reply_desc',
          width: 90,
          sortable: false,
          show: true
        },
        {
          label: '更新',
          prop: 'update_time',
          width: 90,
          sortable: false,
          show: true
        },
        {
          label: '操作',
          prop: 'oper',
          width: 250,
          sortable: false,
          show: true
        }
      ],
      hourPlanDialog: {
        visible: false,
        list: [],
        loading: false,
        datetime: '',
        ad_user_id: '',
        page_size: 10,
        page: 1,
        total: 0
      },
      page_size: 50,
      page: 1,
      total: 0,
      backendUserList: [],
      loading: false,
      search: '',
      shouquanDetailDialog: {
        visible: false,
        selList: [],
        task_id: undefined,
        loading: false,
        list: []
      },
      value1: ['', ''],

      shouquanPlatFormDialog: {
        visible: false,
        platForm: 1
      },
      selectadUserIdsList: []
    }
  },
  watch: {
  },
  created() {
    const url = window.location.href
    let arr = localStorage.getItem(this.storeName)
    if (arr != null && arr.length != this.tableHead.length) {
      localStorage.removeItem(this.storeName)
      arr = localStorage.setItem(this.storeName, JSON.stringify(this.tableHead))
    }
    if (arr) {
      const isClearLocal = JSON.parse(arr).find(
        (item) =>
          item.prop === 'advertiser_id' && (!item.show || item.show === false)
      )
      if (isClearLocal) {
        const newArr = []
        JSON.parse(arr).forEach((item) => {
          if (item !== null) {
            if (!item['show']) {
              item['show'] = true
            }
            newArr.push(item)
          }
        })
        localStorage.setItem(this.storeName, JSON.stringify(newArr))
      }
    } else {
      localStorage.setItem(this.storeName, JSON.stringify(this.tableHead))
    }

    var role = Number(window.localStorage.getItem('role'))
    const date = new Date()
    const year = date.getFullYear() // 获取完整的年份(4位)
    let month = date.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
    let strDate = date.getDate() // 获取当前日(1-31)
    if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
    if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
    this.value1 = [
      `${year}-${month}-${strDate}`,
      `${year}-${month}-${strDate}`
    ];
    this.getList()
  },
  methods: {
    openCustomModal() {
      this.$refs.dragHeadRef.openCustomModal()
    },
    fresh() {
      this.backendUserList = []
      this.getList()
    },
    async openComment(...args) {
      if (args[0].comment_control) {
        const res = await closeCommentControl({
          ad_user_id: args[0].ad_user_id
        }).catch((e) => e)
        if (res.code === 0) {
          this.$message.success('关闭成功');

          [args[0].ad_user_id].map((id) => {
            this.backendUserList.map((item) => {
              if (id === item.ad_user_id) {
                item.comment_control = false
              }
            })
          })
          // this.getList();
        } else {
          this.$message.error(res.msg)
        }
      } else {
        const res = await openCommentControl({
          ad_user_id: args[0].ad_user_id
        }).catch((e) => e)

        if (res.code === 0) {
          this.$message.success('开启成功');

          // 修改表格单行状态 不刷新列表
          [args[0].ad_user_id].map((id) => {
            this.backendUserList.map((item) => {
              if (id === item.ad_user_id) {
                item.comment_control = true
              }
            })
          })
          // this.getList();
        } else {
          this.$message.error(res.msg)
        }
      }
    },
    handleShouQuan() {
      this.handleshouQuan(this.platForm)
    },
    handleshouQuan(platForm) {
      this.shouquanPlatFormDialog.platForm = platForm
      this.shouquanPlatFormDialog.visible = false
      this.shouquan()
    },
    async shouquan() {
      const that = this
      var id = setInterval(async function() {
        const res = await getRecent().catch((e) => e)
        if (JSON.stringify(res.data) != '{}') {
          clearInterval(id)
          that.shouquanJump(res.data.task_id)
        }
      }, 2000)
      const oauthRes = await oauthUrl().catch((e) => e)
      if (oauthRes.code === 0) {
        var data = {
          channel: this.shouquanPlatFormDialog.platForm,
          token: localStorage.getItem('token'),
          app_id: oauthRes.data.app_id
        }
        var url = oauthRes.data.url + '&state='
        window.open(url + JSON.stringify(data), '_blank', '')
      } else {
        this.$message.error(oauthRes.msg)
      }
    },
    shouquanJump(task_id) {
      // if (window.parent.layui) {
      //   window.parent.layui.miniTab.openNewTabByIframe({
      //     id: "page/table/shouquan.html?id=" + id,
      //     href: "page/table/shouquan.html?id=" + id,
      //     title: "授权界面",
      //   });
      // } else {
      //   window.location.href =
      //     "http://bdw.bingdou.site/page/table/shouquan.html?id=" + id;
      // }
      this.shouquanDetailDialog.visible = true
      this.shouquanDetailDialog.task_id = task_id
      this.callBackDetail(task_id)
    },
    async callBackDetail(task_id) {
      this.shouquanDetailDialog.loading = true
      const res = await callBackDetail({
        limit: 300,
        page: 1,
        task_id
      }).catch((e) => e)
      if (res.code === 0) {
        this.shouquanDetailDialog.list = res.data.list
        this.shouquanDetailDialog.loading = false
      } else {
        this.$message.error(res.msg)
        this.shouquanDetailDialog.loading = false
      }
    },
    async checkShouQuanAccount() {
      // 删除拼多多直链
      if (this.shouquanDetailDialog.selList.length === 0) {
        this.$message.error('请选择要授权的帐号')
        return
      }
      const { task_id } = this.shouquanDetailDialog
      const res = await callBackChoose({
        task_id,
        ids: this.shouquanDetailDialog.selList
      }).catch((e) => e)
      if (res.code === 0) {
        this.$message.success('授权成功')
        this.shouquanDetailDialog.selList = []
        this.callBackDetail(task_id)
      } else {
        this.$message.error(res.msg)
        this.callBackDetail(task_id)
      }
    },
    openHourPlanListDialog(ad_user_id) {
      const date = new Date()
      const year = date.getFullYear() // 获取完整的年份(4位)
      let month = date.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
      let strDate = date.getDate() // 获取当前日(1-31)
      if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
      if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
      this.hourPlanDialog.ad_user_id = ad_user_id
      this.hourPlanDialog.visible = true
      this.hourPlanDialog.datetime = `${year}-${month}-${strDate}`
      this.getHourList()
    },
    async getHourList() {
      const { page_size, page, datetime, ad_user_id } = this.hourPlanDialog
      const res = await getHourPlanList({
        ad_user_id,
        datetime
      }).catch((e) => e)
      if (res.code === 0) {
        this.hourPlanDialog.list = res.data.list
        this.hourPlanDialog.total = res.data.total
        this.hourPlanDialog.loading = false
      } else {
        this.$message.error(res.msg)
        this.hourPlanDialog.loading = false
      }
    },
    searchData() {
      this.getList()
    },
    async getList(obj, isAll) {
      // console.log('obj', obj)
      const {
        page_size,
        page
      } = this
      if (!isAll) {
        this.loading = true
      }
      const res = await getBackendList({
        page_size: isAll ? 9999 : page_size,
        page
      }).catch((e) => e)
      this.$refs.dragHeadRef.renderTable()
      this.loading = false

      // console.log('getBackendList', res)
      if (res.code === 0) {
        this.selectadUserIdsList = []
        this.total = Number(res.data.total)

        this.backendUserList = res.data.list
      } else {
        this.backendUserList = []
        this.$message.error(res.msg)
      }
    },
    handelShouquanListChange(val) {
      if (val.length > 0) {
        this.shouquanDetailDialog.selList = val.map((item) => item.ID)
      } else {
        this.shouquanDetailDialog.selList = []
      }
    },

    sort_change(column) {
      this.getList()
    },
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.selectadUserIdsList = val.map((item) => item.ad_user_id)
      } else {
        this.selectadUserIdsList = []
      }
    },
    handleCommand(command) {
      const ad_user_id = command.val.ad_user_id

      const operate = command.val.convert_refund_order === true ? 2 : 1

      const replyStatus = command.val.comment_auto_reply

      switch (command.key) {
        case 'open': // 开启回传退款订单
          this.openRefund(ad_user_id, operate)
          break
        case 'reply': // 自动回复
          this.openReply(ad_user_id, replyStatus)
          break
        case 'hourList': // 小时列表
          this.openHourPlanListDialog(command.val.ad_user_id)
          break
      }
    },
    async openRefund(ad_user_id, operate) {
      const res = await openRefund({
        ad_user_id,
        operate
      }).catch((e) => e)
      if (res.code === 0) {
        this.$message.success(operate == 1 ? '开启成功' : '关闭成功')
        this.backendUserList.map((item) => {
          if (ad_user_id === item.ad_user_id) {
            item.convert_refund_order = operate == 1
          }
        })
      } else {
        this.$message.error(res.msg)
      }
    },
    openPddLinkDialog(...args) {
      // console.log('openPddLinkDialog=======', args[0])
      this.pddLinkDialog.visible = true
      this.getLinearList(args[0].advertiser_id)
    },
    async getLinearList(advertiser_id) {
      const res = await getLinearList({
        advertiser_id
      }).catch((e) => e)
      if (res.code === 0) {
        this.pddLinkDialog.list = res.data
        this.pddLinkDialog.currentAdvertiserId = advertiser_id
      } else {
        this.$message.error(res.msg)
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val

      this.getList()
    }
  }
}
</script>

<style lang="scss">
  html,
  body {
    height: 100%;
  }

  .scroll::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 10px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 12px;
  }

  .scroll::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 8px;
    -webkit-box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.2);
    background: #fff;
  }

  .scroll::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.8);
    border-radius: 10px;
    background: #888;
  }

  .dataPicker {
    white-space: pre;
    margin: 0 10px 0 30px;
  }

  .inputM {
    margin: 0 5px;
    width: 150px;
  }

  .operBtn {
    text-align: center;
  }

  .export-btn {
    display: inline;
    margin-left: 10px;
  }

  .pddTable {
    .el-table .cell {
      // white-space: nowrap;
      // overflow: hidden;
      // text-overflow: ellipsis;
    }
  }

  .el-range-editor--small .el-range-separator {
    margin: 0 10px !important;
  }
</style>
